﻿@model ProductModel

@using SDF.Core.Domain.Catalog
@using SDF.Services

<div class="panel-group">
    <p>
        @T("Admin.Catalog.Products.ProductAttributes.Hint")
    </p>
    @if (Model.Id > 0)
    {
        if (Model.AvailableProductAttributes.Count > 0)
        {
            <div id="productattribute-edit" class="nav-tabs-custom">
                <ul class="nav nav-tabs">
                    @Html.RenderBootstrapTabHeader("tab-attributes", @T("Admin.Catalog.Products.ProductAttributes.Attributes"), true, "tab-attributes")
                    @Html.RenderBootstrapTabHeader("tab-attribute-combinations", @T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations"))
                </ul>
                <div class="tab-content">
                    @Html.RenderBootstrapTabContent("tab-attributes", @TabAttributes(), true, "tab-attributes")
                    @Html.RenderBootstrapTabContent("tab-attribute-combinations", @TabAttributeCombinations())
                </div>
            </div>
        }
        else
        {
            <div class="panel panel-default">
                <div class="panel-body">
                    @T("Admin.Catalog.Products.ProductAttributes.NoAttributesAvailable")
                </div>
            </div>
        }
    }
    else
    {
        <div class="panel panel-default">
            <div class="panel-body">
                @T("Admin.Catalog.Products.ProductAttributes.SaveBeforeEdit")
            </div>
        </div>
    }
</div>

@helper TabAttributes()
{
    <div class="panel panel-default">
        <div class="panel-body">
            <div id="productattributemappings-grid"></div>
            <script>
                $(document).ready(function() {
                    $("#productattributemappings-grid").kendoGrid({
                        dataSource: {
                            type: "json",
                            transport: {
                                read: {
                                    url: "@Html.Raw(Url.Action("ProductAttributeMappingList", "Product", new { productId = Model.Id }))",
                                    type: "POST",
                                    dataType: "json",
                                    data: addAntiForgeryToken
                                },
                                create: {
                                    url: "@Html.Raw(Url.Action("ProductAttributeMappingInsert", "Product", new { productId = Model.Id }))",
                                    type: "POST",
                                    dataType: "json",
                                    data: addAntiForgeryToken
                                },
                                update: {
                                    url: "@Html.Raw(Url.Action("ProductAttributeMappingUpdate", "Product"))",
                                    type: "POST",
                                    dataType: "json",
                                    data: addAntiForgeryToken
                                },
                                destroy: {
                                    url: "@Html.Raw(Url.Action("ProductAttributeMappingDelete", "Product"))",
                                    type: "POST",
                                    dataType: "json",
                                    data: addAntiForgeryToken
                                }
                            },
                            schema: {
                                data: "Data",
                                total: "Total",
                                errors: "Errors",
                                model: {
                                    id: "Id",
                                    fields: {
                                        ProductAttribute: { editable: true, type: "string" },
                                        ProductAttributeId: { editable: true, type: "number" },
                                        TextPrompt: { editable: true, type: "string" },
                                        IsRequired: { editable: true, type: "boolean" },
                                        AttributeControlType: { editable: true, type: "string" },
                                        AttributeControlTypeId: { editable: true, type: "number" },
                                        //ProductId: { editable: false, type: "number" },
                                        DisplayOrder: { editable: true, type: "number" },
                                        ShouldHaveValues: { editable: false, type: "boolean" },
                                        TotalValues: { editable: false, type: "number" },
                                        ValidationRulesAllowed: { editable: false, type: "boolean" },
                                        ConditionAllowed: { editable: false, type: "boolean" },
                                        Id: { editable: false, type: "number" }
                                    }
                                }
                            },
                            requestEnd: function(e) {
                                if (e.type == "create" || e.type == "update") {
                                    this.read();
                                }
                            },
                            error: function(e) {
                                display_kendoui_grid_error(e);
                                // Cancel the changes
                                this.cancelChanges();
                            },
                            serverPaging: true,
                            serverFiltering: true,
                            serverSorting: true
                        },
                        pageable: {
                            refresh: true,
                            numeric: false,
                            previousNext: false,
                            info: false
                        },
                        toolbar: [{ name: "create", text: "@T("Admin.Common.AddNewRecord")" }],
                        edit: function(e) {
                            if (e.model.isNew()) {
                                //little hack here
                                //pre-select the first value of kendoui dropdownlist datasource
                                //for some reasons (maybe, bug) it always sends 0
                                //if no value has been selected (changed) in the dropdownlist
                                if (allProductAttributes.length > 0) {
                                    e.model.ProductAttributeId = allProductAttributes[0].Id;
                                }
                                if (allAttributeControlTypes.length > 0) {
                                    e.model.AttributeControlTypeId = allAttributeControlTypes[0].Id;
                                }
                            }
                        },
                        editable: {
                            confirmation: "@T("Admin.Common.DeleteConfirmation")",
                            mode: "inline"
                        },
                        scrollable: false,
                        columns: [
                            {
                                field: "ProductAttributeId",
                                title: "@T("Admin.Catalog.Products.ProductAttributes.Attributes.Fields.Attribute")",
                                width: 250,
                                editor: productAttributeDropDownEditor,
                                template: "#:ProductAttribute#"
                            }, {
                                field: "TextPrompt",
                                title: "@T("Admin.Catalog.Products.ProductAttributes.Attributes.Fields.TextPrompt")",
                                width: 150
                            }, {
                                field: "IsRequired",
                                title: "@T("Admin.Catalog.Products.ProductAttributes.Attributes.Fields.IsRequired")",
                                width: 150,
                                headerAttributes: { style: "text-align:center" },
                                attributes: { style: "text-align:center" },
                                template: '# if(IsRequired) {# <i class="fa fa-check true-icon"></i> #} else {# <i class="fa fa-close false-icon"></i> #} #'
                            },
                            {
                                field: "AttributeControlTypeId",
                                title: "@T("Admin.Catalog.Products.ProductAttributes.Attributes.Fields.AttributeControlType")",
                                width: 250,
                                editor: attributeControlTypeDropDownEditor,
                                template: "#:AttributeControlType#"
                            },
                            {
                                field: "DisplayOrder",
                                title: "@T("Admin.Catalog.Products.ProductAttributes.Attributes.Fields.DisplayOrder")",
                                width: 150,
                                //integer format
                                format: "{0:0}"
                            }, {
                                field: "ShouldHaveValues",
                                title: "@T("Admin.Catalog.Products.ProductAttributes.Attributes.Values")",
                                width: 150,
                                template: '# if(ShouldHaveValues) {# <a href="@Url.Content("~/Admin/Product/EditAttributeValues/")?productAttributeMappingId=#=Id#">@T("Admin.Catalog.Products.ProductAttributes.Attributes.Values.ViewLink")</a> <div>@T("Admin.Catalog.Products.ProductAttributes.Attributes.Values.TotalValues") #=TotalValues#</div>#}  #'
                            },
                            {
                                field: "ValidationRulesAllowed",
                                title: "@T("Admin.Catalog.Products.ProductAttributes.Attributes.ValidationRules")",
                                width: 150,
                                template: "# if(ValidationRulesAllowed) {# <a href='javascript:OpenWindow(\"@Url.Content("~/Admin/Product/ProductAttributeValidationRulesPopup/")#=Id#?btnId=btnRefreshProductAttributes&formId=product-form\", 800, 320, true);'>@T("Admin.Catalog.Products.ProductAttributes.Attributes.ValidationRules.ViewLink")</a> <div>#=ValidationRulesString#</div>#}  #"
                            },
                            {
                                field: "ConditionAllowed",
                                title: "@T("Admin.Catalog.Products.ProductAttributes.Attributes.Condition")",
                                width: 150,
                                template: "# if(ConditionAllowed) {# <a href='javascript:OpenWindow(\"@Url.Content("~/Admin/Product/ProductAttributeConditionPopup/")?productAttributeMappingId=#=Id#&btnId=btnRefreshProductAttributes&formId=product-form\", 800, 400, true);'>@T("Admin.Catalog.Products.ProductAttributes.Attributes.Condition.ViewLink")</a> <div>#=ConditionString#</div>#}  #"
                            },
                            {
                                command: [
                                    {
                                        name: "edit",
                                        text: {
                                            edit: "@T("Admin.Common.Edit")",
                                            update: "@T("Admin.Common.Update")",
                                            cancel: "@T("Admin.Common.Cancel")"
                                        }
                                    }, {
                                        name: "destroy",
                                        text: "@T("Admin.Common.Delete")"
                                    }
                                ],
                                width: 200
                            }
                        ]
                    });
                });

                //local datasource
                var allProductAttributes = [
                    @for (int i = 0; i < Model.AvailableProductAttributes.Count; i++)
                    {
                        var productAttributeItem = Model.AvailableProductAttributes[i];
                        <text>
                            {
                                Id: @(productAttributeItem.Value),
                                Name: "@(Html.Raw(HttpUtility.JavaScriptStringEncode(productAttributeItem.Text)))"
                            }
                                </text>
                        if (i != Model.AvailableProductAttributes.Count - 1)
                        {
                            <text>,</text>
                        }
                    }
                ];

                var allAttributeControlTypes = [
                    @{
                        var allAttributeControlTypes = (from act in AttributeControlType.DropdownList.ToSelectList()
                            select new {Id = act.Value, Name = act.Text}).ToList();
                    }
                            @for (int i = 0; i < allAttributeControlTypes.Count; i++)
                    {
                        var attributeControlType = allAttributeControlTypes[i];
                        <text>
                            {
                                Id: @(attributeControlType.Id),
                                Name: "@(Html.Raw(HttpUtility.JavaScriptStringEncode(attributeControlType.Name)))"
                            }
                            </text>
                        if (i != allAttributeControlTypes.Count - 1)
                        {
                            <text>,</text>
                        }
                    }
                ];

                function productAttributeDropDownEditor(container, options) {
                    $('<input required data-text-field="Name" data-value-field="Id" data-bind="value:ProductAttributeId"/>')
                        .appendTo(container)
                        .kendoDropDownList({
                            autoBind: false,
                            dataSource: allProductAttributes
                        });
                }

                function attributeControlTypeDropDownEditor(container, options) {
                    $('<input required data-text-field="Name" data-value-field="Id" data-bind="value:AttributeControlTypeId"/>')
                        .appendTo(container)
                        .kendoDropDownList({
                            autoBind: false,
                            dataSource: allAttributeControlTypes
                        });
                }
            </script>
            <input type="submit" id="btnRefreshProductAttributes" style="display: none" />
            <script type="text/javascript">
                $(document).ready(function () {
                    $('#btnRefreshProductAttributes').click(function () {
                        //refresh grid
                        var grid = $("#productattributemappings-grid").data('kendoGrid');
                        grid.dataSource.read();

                        //return false to don't reload a page
                        return false;
                    });
                });
            </script>
        </div>
    </div>
}

@helper TabAttributeCombinations()
{
    <div class="panel panel-default">
        <div class="panel-body">
            <p>
                @T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.Description")
            </p>

            <div id="attributecombinations-grid"></div>

            <script>
                $(document).ready(function() {
                    $("#attributecombinations-grid").kendoGrid({
                        dataSource: {
                            type: "json",
                            transport: {
                                read: {
                                    url: "@Html.Raw(Url.Action("ProductAttributeCombinationList", "Product", new {productId = Model.Id}))",
                                    type: "POST",
                                    dataType: "json",
                                    data: addAntiForgeryToken
                                },
                                update: {
                                    url: "@Html.Raw(Url.Action("ProductAttributeCombinationUpdate", "Product"))",
                                    type: "POST",
                                    dataType: "json",
                                    data: addAntiForgeryToken
                                },
                                destroy: {
                                    url: "@Html.Raw(Url.Action("ProductAttributeCombinationDelete", "Product"))",
                                    type: "POST",
                                    dataType: "json",
                                    data: addAntiForgeryToken
                                }
                            },
                            schema: {
                                data: "Data",
                                total: "Total",
                                errors: "Errors",
                                model: {
                                    id: "Id",
                                    fields: {
                                        //ProductId: { editable: false, type: "number" },
                                        AttributesXml: { editable: false, type: "string" },
                                        Warnings: { editable: false, type: "string" },
                                        StockQuantity: { editable: true, type: "number" },
                                        AllowOutOfStockOrders: { editable: true, type: "boolean" },
                                        Sku: { editable: true, type: "string" },
                                        ManufacturerPartNumber: { editable: true, type: "string" },
                                        Gtin: { editable: true, type: "string" },
                                        OverriddenPrice: { editable: true, type: "number" },
                                        NotifyAdminForQuantityBelow: { editable: true, type: "number" },
                                        Id: { editable: false, type: "number" }
                                    }
                                }
                            },
                            requestEnd: function(e) {
                                if (e.type == "update") {
                                    this.read();
                                }
                            },
                            error: function(e) {
                                display_kendoui_grid_error(e);
                                // Cancel the changes
                                this.cancelChanges();
                            },
                            serverPaging: true,
                            serverFiltering: true,
                            serverSorting: true
                        },
                        pageable: {
                            refresh: true,
                            numeric: false,
                            previousNext: false,
                            info: false
                        },
                        editable: {
                            confirmation: "@T("Admin.Common.DeleteConfirmation")",
                            mode: "inline"
                        },
                        scrollable: false,
                        columns: [
                            {
                                field: "AttributesXml",
                                title: "@T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.Fields.Attributes")",
                                width: 400,
                                template: "#=AttributesXml# # if(Warnings !== null) {# <div><span style=\"color: red\">#=Warnings#</span></div> #}  #",
                                encoded: false
                            }, {
                                field: "StockQuantity",
                                title: "@T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.Fields.StockQuantity")",
                                width: 150,
                                //integer format
                                format: "{0:0}"
                            }, {
                                field: "AllowOutOfStockOrders",
                                title: "@T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.Fields.AllowOutOfStockOrders")",
                                width: 150,
                                headerAttributes: { style: "text-align:center" },
                                attributes: { style: "text-align:center" },
                                template: '# if(AllowOutOfStockOrders) {# <i class="fa fa-check true-icon"></i> #} else {# <i class="fa fa-close false-icon"></i> #} #'
                            }, {
                                field: "Sku",
                                title: "@T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.Fields.Sku")",
                                width: 200
                            }, {
                                field: "ManufacturerPartNumber",
                                title: "@T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.Fields.ManufacturerPartNumber")",
                                width: 200
                            }, {
                                field: "Gtin",
                                title: "@T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.Fields.Gtin")",
                                width: 200
                            }, {
                                field: "OverriddenPrice",
                                title: "@T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.Fields.OverriddenPrice")",
                                width: 200,
                                editor: function(container, options) {
                                    $('<input name="' + options.field + '"/>')
                                        .appendTo(container)
                                        .kendoNumericTextBox({
                                            format: "{0:n4}",
                                            decimals: 4
                                        });
                                }
                            }, {
                                field: "NotifyAdminForQuantityBelow",
                                title: "@T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.Fields.NotifyAdminForQuantityBelow")",
                                width: 150,
                                //integer format
                                format: "{0:0}"
                            }, {
                                command: [
                                    {
                                        name: "edit",
                                        text: {
                                            edit: "@T("Admin.Common.Edit")",
                                            update: "@T("Admin.Common.Update")",
                                            cancel: "@T("Admin.Common.Cancel")"
                                        }
                                    }, {
                                        name: "destroy",
                                        text: "@T("Admin.Common.Delete")"
                                    }
                                ],
                                width: 200
                            }
                        ]
                    });
                });
            </script>

            <input type="submit" id="btnRefreshCombinations" style="display: none" />
            <script type="text/javascript">
                $(document).ready(function() {
                    //refresh button
                    $('#btnRefreshCombinations').click(function() {
                        //refresh grid
                        var grid = $("#attributecombinations-grid").data('kendoGrid');
                        grid.dataSource.read();

                        //return false to don't reload a page
                        return false;
                    });
                
                    //generate combinations
                    $('#btnGenerateAllCombinations').click(function() {
                        if (confirm('@T("Admin.Common.AreYouSure")')) {

                            var postData = {

                            };
                            addAntiForgeryToken(postData);

                            $.ajax({
                                cache: false,
                                type: 'POST',
                                url: '@Url.Action("GenerateAllAttributeCombinations", "Product", new {productId = Model.Id})',
                                data: postData,
                                dataType: 'json',
                                success: function(data) {
                                    //refresh grid
                                    var grid = $("#attributecombinations-grid").data('kendoGrid');
                                    grid.dataSource.read();
                                },
                                error: function(xhr, ajaxOptions, thrownError) {
                                    alert('Error while generating attribute combinations');
                                }
                            });
                        }
                        return false;
                    });
                });
            </script>
        </div>
        <div class="panel-footer">
            <button type="submit" id="btnAddNewCombination" onclick="javascript:OpenWindow('@(Url.Action("AddAttributeCombinationPopup", "Product", new {productId = Model.Id, btnId = "btnRefreshCombinations", formId = "product-form"}))', 800, 700, true); return false;" class="btn btn-primary">
                @T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.AddNew")
            </button>
            <button type="button" id="btnGenerateAllCombinations" class="btn bg-aqua">@T("Admin.Catalog.Products.ProductAttributes.AttributeCombinations.GenerateAll")</button>
        </div>
    </div>
}
